package com.pjmike.netty.client;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundBuffer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author bj
 * @Description 记录链接channel,并用于发送消息
 * @Param
 * @return
 **/
@Component("nettyMessageUtil")
@Slf4j
public class NettyMessageUtil {
    //保存设备号和通道的映射
    private static ConcurrentHashMap<String, ChannelHandlerContext> map = new ConcurrentHashMap<>();

    public static void registerSB(String sbbh,ChannelHandlerContext ctx){
        map.put(sbbh,ctx);
    }

    public void sendMsg(String sbbh,Object msg){
        if(map.get(sbbh)!=null){
            if(map.get(sbbh).channel().isActive()){
                map.get(sbbh).channel().writeAndFlush(msg);
            }
        }else{
            throw new RuntimeException("设备尚未注册");
        }
    }
}
